define(['jquery', 'bootstrap', 'mbti', 'form', 'template'], function ($, undefined, Mbti, Form, Template) {
    var Controller = {
        evaluateId: 0,
        sceneId: 0,
        events:{
            addSubClick: function(){
                $(".sub").off("click");
                $(".sub").click(function(){
                    if($(".evaluate .selected").length < $(".evaluate").length){
                        const noAnswers = [];
                        $(".evaluate").each(function (index, item){
                            if(($(item).find(".selected")?.length || 0) == 0){
                                noAnswers.push($(item).data("index"));
                            }
                        });
                        layer.alert("请回答第"+noAnswers.join(",")+"题后再操作");
                    }else{
                        const answers = [];
                        $(".evaluate .selected").each(function (index, item){
                            answers.push($(item).data("answer"));
                        });
                        $.ajax({
                            url: Fast.api.fixurl('evaluate/add_record'), // 请求的URL
                            type: 'post', //请求类型,若为post,则表示发送post请求
                            data: {
                                "id": parseInt(Controller.evaluateId),
                                "answers": answers,
                                "scene_id": parseInt(Controller.sceneId),
                                "sex": Config.sex,
                                "birthday": Config.birthday
                            },
                            dataType: 'json',  // 接收的数据类型
                            isAsync: false,     // 是否异步请求
                            success: function(data) {
                                if(parseInt(data?.code||"0") == 0){
                                    layer.alert(data?.msg||"操作失败");
                                }else{
                                    Controller.evaluateId = parseInt(data?.data);
                                    const appletBtn = document.getElementById('launch-btn');
                                    if(appletBtn){
                                        appletBtn.setAttribute("path",Config.applet_path+"?scene_id="+Controller.sceneId+"&evaluate_id="+Controller.evaluateId);
                                    }
                                    layer.msg(data?.msg||"操作成功",function(){
                                        if(wx?.ready){
                                            wx.ready(function(){
                                                if(wx?.miniProgram?.getEnv){
                                                    wx?.miniProgram?.getEnv(function(res) {
                                                        if(res?.miniprogram && appletBtn){
                                                            /*
                                                            wx?.miniProgram?.redirectTo({
                                                                url:'/pages/mbti/result?scene_id='+parseInt(Controller.sceneId)+'&evaluate_id='+Controller.evaluateId
                                                            });
                                                            */
                                                            $(appletBtn).replaceWith('<div class="show_res" id="show_res">查看结果</div>');
                                                            $("#show_res").click(function(){
                                                                wx?.miniProgram?.redirectTo({
                                                                    url:'/pages/mbti/result?scene_id='+parseInt(Controller.sceneId)+'&evaluate_id='+Controller.evaluateId
                                                                });
                                                            });
                                                        }
                                                        $("#get_result").removeClass("hidden");
                                                    });
                                                }else{
                                                    $("#get_result").removeClass("hidden");
                                                }
                                            });
                                        }else{
                                            $("#get_result").removeClass("hidden");
                                        }
                                    });
                                }
                            },
                            error: function(err) {
                                console.log("--------操作失败--------", err);
                                layer.alert("操作失败");
                            }
                        });
                    }
                });
            },
            addNextClick: function(){
                $(".next").off("click");
                $(".next").click(function(){
                    const currIndex = parseInt($(".show").data("index"));
                    if(currIndex < $(".evaluate").length){
                        $("#index_box_"+currIndex).removeClass("show");
                        $("#index_box_"+(currIndex+1)).addClass("show");
                        $("#numerator").html($("#index_box_"+(currIndex+1)).data("index"));
                        const percentAge = parseInt($("#index_box_"+(currIndex+1)).data("index"))*100/($(".evaluate").length ? $(".evaluate").length : 1);
                        $("#progress-bar").attr("aria-valuenow", percentAge);
                        $("#progress-bar").css("width", percentAge+"%");
                        if((currIndex+1) == $(".evaluate").length){
                            $(".next").replaceWith('<div class="sub">提交</div>');
                            Controller.events.addSubClick();
                        }
                    }else{
                        layer.msg("已到最后一题");
                    }
                });
            }
        },
        index: function () {
            $(document).ready(function(){
                Controller.evaluateId = parseInt(Config.evaluate_id);
                Controller.sceneId = parseInt(Config.scene_id);
                const appletBtn = document.getElementById('launch-btn');
                appletBtn.addEventListener('launch', function (e) {
                    wx.closeWindow();
                });
                appletBtn.addEventListener('error', function (e) {
                    console.log('fail', e.detail);
                });
                if(Controller.evaluateId > 0){
                    if(appletBtn){
                        appletBtn.setAttribute("path",Config.applet_path+"?scene_id="+Controller.sceneId+"&evaluate_id="+Controller.evaluateId);
                        /*
                        if(wx?.ready) {
                            wx.ready(function () {
                                if (wx?.miniProgram?.getEnv) {
                                    wx?.miniProgram?.getEnv(function (res) {
                                        if (res?.miniprogram) {
                                            $(appletBtn).replaceWith('<div class="show_res" id="show_res">查看结果</div>');
                                            $("#show_res").click(function(){
                                                wx?.miniProgram?.redirectTo({
                                                    url:'/pages/mbti/result?scene_id='+parseInt(Controller.sceneId)+'&evaluate_id='+Controller.evaluateId
                                                });
                                            });
                                        }
                                    });
                                }
                            });
                        }
                        */
                    }
                    //$("#get_result").removeClass('hidden');
                }
                $(".answers").click(function(){
                    const parentEvaluate = $(this).parent(".evaluate");
                    const allCount = $(".evaluate").length;
                    parentEvaluate.find(".answers").removeClass("selected");
                    $(this).addClass("selected");
                    if(parseInt(parentEvaluate.data("index")) == allCount){
                        $(".next").replaceWith('<div class="sub">提交</div>');
                        Controller.events.addSubClick();
                    }else{
                        setTimeout(function(){
                            parentEvaluate.removeClass("show");
                            parentEvaluate.next().addClass("show");
                            $("#numerator").html(parentEvaluate.next().data("index"));
                            const percentAge = parseInt(parentEvaluate.next().data("index"))*100/($(".evaluate").length ? $(".evaluate").length : 1);
                            $("#progress-bar").attr("aria-valuenow", percentAge);
                            $("#progress-bar").css("width", percentAge+"%");
                            if(($(".sub")?.length || 0) > 0){
                                $(".sub").replaceWith('<div class="next">下一题 <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span></div>');
                                Controller.events.addNextClick();
                            }
                        }, 300);
                    }
                });
                $(".previous").click(function(){
                    const currIndex = parseInt($(".show").data("index"));
                    if(currIndex > 1){
                        $("#index_box_"+currIndex).removeClass("show");
                        $("#index_box_"+(currIndex-1)).addClass("show");
                        $("#numerator").html((currIndex-1));
                        const percentAge = (parseInt(currIndex) -1 )*100/($(".evaluate").length ? $(".evaluate").length : 1);
                        $("#progress-bar").attr("aria-valuenow", percentAge);
                        $("#progress-bar").css("width", percentAge+"%");
                        if(($(".sub")?.length || 0) > 0){
                            $(".sub").replaceWith('<div class="next">下一题 <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span></div>');
                            Controller.events.addNextClick();
                        }
                    }else{
                        layer.msg("已到第一题");
                    }
                });
                Controller.events.addNextClick();
                if(Config?.wx_config){
                    wx.config(Config?.wx_config);
                    wx.ready(function(){
                        wx.updateAppMessageShareData({
                            ...Config?.wx_share,
                            success: function (res) {
                                console.log("------------设置成功------------", res);
                            }
                        });
                        wx.updateTimelineShareData({
                            ...Config?.wx_share,
                            success: function () {
                                console.log("------------设置分享朋友圈成功------------", res);
                            }
                        });
                    });
                }
            });
        },
        get_result: function () {},
        show_result: function () {
            const canvas = document.getElementById('canvas');
            const ctx = canvas.getContext('2d');
            function resizeCanvas() {
                canvas.width = window.innerWidth;
                canvas.height = window.innerHeight > document.documentElement.scrollHeight ? window.innerHeight : document.documentElement.scrollHeight;
            }
            resizeCanvas();
            window.addEventListener('resize', resizeCanvas);
            // 圆形参数
            const columns = 5;//绘制圆形的列数
            const radius = canvas.width / columns / 2;// 计算直径
            const rows = Math.floor(canvas.height / radius);
            function draw() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                for(let row = 0; row < rows ; row++){
                    for(let col = 0; col < columns ; col++){
                        const posX = radius * ( 2 * col + 1 );
                        const posY = radius * ( 2 * row + 1 );
                        ctx.beginPath();
                        ctx.arc(posX, posY, radius, 0, Math.PI * 2);
                        ctx.fillStyle = "rgba("+Config?.color_solution?.bg_cycle_rgb?.[0]+", "+Config?.color_solution?.bg_cycle_rgb?.[1]+", "+Config?.color_solution?.bg_cycle_rgb?.[2]+", "+( 1 - row/rows )+")";
                        ctx.fill();
                    }
                }
            }
            draw();
            if(Config?.wx_config){
                wx.config(Config?.wx_config);
                wx.ready(function(){
                    wx.updateAppMessageShareData({
                        ...Config?.wx_share,
                        success: function (res) {
                            console.log("------------设置成功------------", res);
                        }
                    });
                    wx.updateTimelineShareData({
                        ...Config?.wx_share,
                        success: function () {
                            console.log("------------设置分享朋友圈成功------------", res);
                        }
                    });
                    if(wx?.miniProgram?.getEnv){
                        wx?.miniProgram?.getEnv(function(res) {
                            if(res?.miniprogram){
                                $("#re_evaluate,#get_mine").click(function(){
                                    wx?.miniProgram?.redirectTo({
                                        url:'/pages/mbti/index?scene_id='+parseInt(Config.scene_id)
                                    });
                                });
                            }else{
                                $("#re_evaluate,#get_mine").click(function(){ window.location.href = Fast.api.fixurl('mbti/index/detail')+'?scene_id='+parseInt(Controller.sceneId); });
                            }
                        });
                    }else{
                        $("#re_evaluate,#get_mine").click(function(){ window.location.href = Fast.api.fixurl('mbti/index/detail')+'?scene_id='+parseInt(Controller.sceneId); });
                    }
                });
            }
        }
    };
    return Controller;
});